package com.rocketmq.temp3.rocketmq.listener;

import com.rocketmq.temp3.common.components.TransactionUtils;
import com.rocketmq.temp3.common.utils.GenerateUtils;
import com.rocketmq.temp3.common.utils.JacksonUtils;
import com.rocketmq.temp3.entity.po.Product;
import com.rocketmq.temp3.repository.base.BaseDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;

@Slf4j
@Component
@RocketMQTransactionListener(txProducerGroup = "mq-producer-group")
public class SyncProducerListener implements RocketMQLocalTransactionListener {

    @Autowired
    protected BaseDao<Product> productBaseDao;

    /**
     * 执行我们创建订单的事务
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        MessageHeaders headers = message.getHeaders();
        Object msg = headers.get("msg");
        if (msg == null) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }

        TransactionStatus begin = null;
        try {
            begin = TransactionUtils.begin();

            Product product = JacksonUtils.from(String.valueOf(msg), Product.class);
            int rows = productBaseDao.insert(product);
            if (rows > 0) {
                TransactionUtils.commit(begin);
                // 告诉Broker可以消费 这条消息了
                return RocketMQLocalTransactionState.COMMIT;
            }
        } catch (Exception ex) {
            log.error(GenerateUtils.printException(ex));
            if (begin != null) {
                TransactionUtils.rollback(begin);
            }
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

    /**
     * 提供给我们的Broker定时检查
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        MessageHeaders headers = message.getHeaders();
        Object msg = headers.get("msg");
        if (msg == null) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }

        Product product = JacksonUtils.from(String.valueOf(msg), Product.class);
        assert product != null;

        if (null == productBaseDao.selectByPrimaryKey(product.getProductId())) {
            return RocketMQLocalTransactionState.UNKNOWN;
        } else {
            return RocketMQLocalTransactionState.COMMIT;
        }
    }
}
